<?php
/**
 * 公共函数
 */

/**---------------------------------------------
 *  字符串相关函数
 * ---------------------------------------------
 */
if (!function_exists('getRandStr')) {
    /**
     * 随机生成字符串
     * @param int $len
     * @return string
     */
    function getRandStr($len)
    {
        $chars = array(
            "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
            "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g",
            "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
            "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3",
            "4", "5", "6", "7", "8", "9"
        );
        $charsLen = count($chars) - 1;
        shuffle($chars);
        $output = "";
        for ($i = 0; $i < $len; $i++) {
            $output .= $chars[mt_rand(0, $charsLen)];
        }
        return $output;
    }
}

if (!function_exists('base62_encode')) {
    /**
     * Convert a 10 base numeric string to a 62 base string
     * @param  int $value
     * @return string
     */
    function base62_encode($value)
    {
        return to_base($value, 62);
    }
}

if (!function_exists('base62_decode')) {
    /**
     * Convert a string from base 62 to base 10 numeric string
     * @param  string $value
     * @return int
     */
    function base62_decode($value)
    {
        return to_base10($value, 62);
    }
}

if (!function_exists('to_base')) {

    /**
     * Convert a numeric string from base 10 to another base.
     * @param $value  decimal string
     * @param int $b base , max is 62
     * @return string
     */
    function to_base($value, $b = 62)
    {
        $base = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $r = $value % $b;
        $result = $base[$r];
        $q = floor($value / $b);
        while ($q) {
            $r = $q % $b;
            $q = floor($q / $b);
            $result = $base[$r] . $result;
        }
        return $result;
    }
}

if (!function_exists('to_base10')) {
    /**
     * Convert a string from a given base to base 10.
     * @return string
     */
    function to_base10($value, $b = 62)
    {
        $base = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $limit = strlen($value);
        $result = strpos($base, $value[0]);
        for ($i = 1; $i < $limit; $i++) {
            $result = $b * $result + strpos($base, $value[$i]);
        }
        return $result;
    }
}

if (!function_exists('md5_rand')) {
    /**
     * Convert a string from a given base to base 10.
     * @return string
     */
    function md5_rand()
    {
        $time = time();
        $numRand = getRandStr(10);
        return strtoupper(md5($time . $numRand));
    }
}

if (!function_exists('code62')) {
    /**
     * 生成短网址
     * @param $x
     * @return string
     */
    function code62($x)
    {
        $show = '';
        while($x > 0){
            $s = $x % 62;
            if ($s > 35){
                $s = chr($s + 61);
            }elseif($s > 9 && $s <= 35){
                $s = chr($s + 55);
            }
            $show .= $s;
            $x = floor($x / 62);
        }
        return $show;
    }
}

if (!function_exists('short_url')) {
    /**
     * 生成短链
     * @param $url
     * @return string
     */
    function short_url($url)
    {
        $url = crc32($url);
        $result = sprintf("%u",$url);
        return code62($result);
    }
}

if (!function_exists('calc_float')) {
    function calc_float($type, $m, $n, $scale = 2) {
        $result = '';
        switch ($type) {
            case 'add':
                $result = bcadd($m, $n, $scale);
                break;
            case 'sub':
                $result = bcsub($m, $n, $scale);
                break;
            case 'mul':
                $result = bcmul($m, $n, $scale);
                break;
            case 'div':
                $result = bcdiv($m, $n, $scale);
                break;
        }
        return $result;
    }
}

if (!function_exists('generate_rand_id')) {
    function generate_rand_id() {
        return getRandStr(8) . '-' . getRandStr(4) . '-' . getRandStr(4) . '-' . getRandStr(4) . '-' . getRandStr(12);
    }
}

if (!function_exists('uuid')) {
    /**
     * 获取全球唯一标识
     * @return string
     */
    function uuid()
    {
        return sprintf(
            '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff)
        );
    }
}
if (!function_exists('is_true')) {
    /**
     * 将字符串的true 跟 false 转换成布尔值
     * @param $val
     * @param bool $return_null
     * @return bool|mixed|null
     */
    function is_true($val, $return_null=false){
        $boolval = ( is_string($val) ? filter_var($val, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) : (bool) $val );
        return ( $boolval===null && !$return_null ? false : $boolval );
    }
}
if (!function_exists('p')) {
    /**
     * 传递数据以易于阅读的样式格式化后输出
     * @param $data
     */
    function p($data)
    {
        $array = [];
        // 定义样式
        echo '<pre style="display: block;font-size: 12px;line-height: 1.42857;color: #13db1d;word-break: break-all;word-wrap: break-word;background-color: #000000;border: 1px solid #CCC;border-radius: 4px;">';
        foreach($data as $key=>$value) {
            $array[$key] = json_decode(json_encode($value), true);
        }
        print_r($array);
        echo '</pre>';

    }
}
if (!function_exists('pd')) {
    // 传递数据以易于阅读的样式格式化后输出并终止
    function pd($data)
    {
        p($data);
        die;
    }
}




/**---------------------------------------------
 *  数组相关函数
 * ---------------------------------------------
 */
if (!function_exists('cleanArrayNull')) {
    /**
     * 去除数组中含有null值
     * @param $arr
     * @return array
     */
    function cleanArrayNull($arr)
    {
      if (empty($arr)) return [];

      foreach ($arr as $key => $val) {
          if (is_null($val)) unset($arr[$key]);
      }

      return $arr;
    }
}

if (!function_exists('changeKeysToNum')) {
    /**
     * 把数组的键值转换为数字整形
     * @param array $arr 待转换的数组
     * @return array
     */
    function changeKeysToNum($arr, $except = []){
        if (!is_array($arr)) return $arr;

        $i = 0;
        $new = array();
        foreach ($arr as $key => $value) {
            if(is_array($value) && !in_array($key, $except)){
                $new[$i] = changeKeysToNum($value, $except);
            } else {
                $new[$key] = $value;
            }
            $i++;
        }
        return $new;
    }
}

if (!function_exists('getArraysByLimit')) {
    /**
     * 截取数组某部分
     * @param $arr
     * @param $cur
     * @param $size
     * @return mixed
     */
    function getArraysByLimit($arr, $cur, $size) {
        if (!is_array($arr)) return $arr;

        $cur_page = $cur ?? 1;
        $page_size = $size ?? 20;

        $offset = ($cur_page- 1) * $page_size;
        $limit  = $page_size;
        $newArr = array_slice($arr, $offset, $limit);
        return $newArr;
    }
}


if (!function_exists('arrayToStringArray')) {
    /**
     * 将数组转换成字符串形式的住宿
     * @param $arr
     * @return mixed
     */
    function arrayToStringArray($arr) {
        if (!is_array($arr) || empty($arr)) return $arr;
        $str = '[';
        foreach ($arr as $key => $val) {
            if (is_string($val)) {
                $str .= '"' . $val . '",';
            }else {
                $str .= $val . ',';
            }
        }
        $str = substr($str, 0, -1);
        $str .= ']';

        return $str;
    }
}

if (!function_exists('arrayToTree')) {
    /**
     * 一维无层级字段的数组根据父级ID转换为属性结构数组
     * @param array $data [需要转换的数据]
     * @param string $pkName [主键ID字段名称]
     * @param string $pIdName [父级ID字段名称]
     * @param string $childName [保存子级数据的字段]
     * @param bool $emptyChildren [当没有子级数据时是否显示空的子级字段]
     * @param string $rootId [根ID]
     * @return array
     */
    function arrayToTree($data, $pkName='id', $pIdName='parent_id', $childName='children', $emptyChildren=false, $rootId='') {
        $returnData = [];
        foreach($data as $v){
            if($v[$pIdName] == $rootId){
                $res = arrayToTree($data, $pkName, $pIdName, $childName, $emptyChildren, $v[$pkName]);
                if(!empty($res)){
                    $v[$childName] = $res;
                } else {
                    if ($emptyChildren) {
                        $v[$childName] = [];
                    }
                }
                $returnData[] = $v;
            }
        }
        return $returnData;
    }
}

if (!function_exists('objToArray')) {
    /**
     * 对象转数组
     * @param string $data
     * @return array|mixed
     */
    function objToArray($data = ''){
        if (empty($data)) return [];
        return json_decode(json_encode($data),true);
    }
}


if (!function_exists('is_json')) {
    /**
     * 判断是否是json
     * @param string $string
     * @return bool
     */
    function is_json($string) {
        if(!is_string($string)) return false;
        json_decode($string);
        if(json_last_error() == JSON_ERROR_NONE) return false;
        return true;
    }
}


if (!function_exists('is_url')) {
    /**
     * 判断是否是url
     * @param string $string
     * @return bool
     */    
    function is_url($url){
        $r = "/http[s]?:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is";
        if(preg_match($r,$url)){
            return true;
        }else{
            return false;
        }
    }
}